package com.itcode.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcode.mapper.ArticleMapper;
import com.itcode.pojo.Article;
import com.itcode.pojo.PageBean;
import com.itcode.service.ArticleService;
import com.itcode.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {

        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        final Map<String, Object> map = ThreadLocalUtil.get();
        final Integer id = (Integer) map.get("id");
        article.setCreateUser(id);
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 创建PageBean对象
        PageBean<Article> pb = new PageBean<>();

        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        //调用mapper
        final Map<String, Object> map = ThreadLocalUtil.get();
        final Integer id = (Integer) map.get("id");
        List<Article> list = articleMapper.list(categoryId, state, id);
        Page<Article> p = (Page<Article>) list; //强转

        //将数据填充到PageBean
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    /**
     * 获取文章详情
     * @param id 文章id
     * @return
     */
    @Override
    public Article findById(Integer id) {
        Article article = articleMapper.findById(id);
        return article;
    }

    /**
     * 更新
     * @param article 文章
     */
    @Override
    public void update(Article article) {
        //更新时间
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    /*
    删除
     */
    @Override
    public void remove(Integer id) {
        articleMapper.deleteById(id);
    }
}
